<template>
  <div class="fujianjianli-page">
    <!-- 标题栏 -->
    <van-nav-bar
      title="附件简历"
      left-arrow
      @click-left="goBack"
      fixed
      placeholder
    />

    <!-- 主容器 -->
    <div class="fujianjianli-container">
      <!-- 侧边导航栏 -->
      <van-sidebar
        v-model="activeKey"
        @change="onSidebarChange"
        class="sidebar"
      >
        <van-sidebar-item title="投递简历移除" />
        <van-sidebar-item title="新增简历" />
        <van-sidebar-item title="简历列表" />
        <van-sidebar-item title="简历移除" />
      </van-sidebar>

      <!-- 内容区域 -->
      <div class="content">
        <!-- 投递简历移除 -->
        <div v-if="activeKey === 0" class="delivery-remove-section">
          <div class="section-title">投递简历移除</div>

          <!-- 搜索框 -->
          <div class="search-box">
            <van-field
              v-model="deliverySearchKeyword"
              placeholder="请输入简历ID或关键词搜索"
              clearable
              @keyup.enter="searchDeliveryResumes"
            >
              <template #button>
                <van-button
                  type="primary"
                  size="small"
                  @click="searchDeliveryResumes"
                  :loading="deliverySearchLoading"
                >
                  搜索
                </van-button>
              </template>
            </van-field>
          </div>

          <!-- 投递简历列表 -->
          <div class="resume-list">
            <van-list
              v-model:loading="deliveryLoading"
              :finished="deliveryFinished"
              finished-text="没有更多了"
              @load="loadDeliveryResumes"
            >
              <van-cell
                v-for="item in deliveryResumeList"
                :key="item.id"
                :title="item.title || '简历标题'"
                :label="`投递时间: ${formatDate(item.createdAt)}`"
                is-link
                @click="showDeliveryDetail(item)"
              >
                <template #right-icon>
                  <van-button
                    type="danger"
                    size="small"
                    @click.stop="removeDeliveryResume(item)"
                    :loading="item.removing"
                  >
                    移除
                  </van-button>
                </template>
              </van-cell>
            </van-list>
          </div>

          <!-- 投递简历详情弹窗 -->
          <van-popup
            v-model:show="showDeliveryDetailPopup"
            position="bottom"
            :style="{ height: '60%' }"
            round
          >
            <div class="detail-content">
              <div class="detail-header">
                <h3>投递简历详情</h3>
                <van-icon name="cross" @click="closeDeliveryDetail" />
              </div>
              <div class="detail-body">
                <div v-if="selectedDeliveryResume">
                  <p>
                    <strong>简历标题:</strong>
                    {{ selectedDeliveryResume.title }}
                  </p>
                  <p>
                    <strong>投递时间:</strong>
                    {{ formatDate(selectedDeliveryResume.createdAt) }}
                  </p>
                  <p>
                    <strong>简历描述:</strong>
                    {{ selectedDeliveryResume.description || "暂无描述" }}
                  </p>
                </div>
              </div>
            </div>
          </van-popup>
        </div>

        <!-- 新增简历 -->
        <div v-else-if="activeKey === 1" class="add-resume-section">
          <div class="section-title">新增简历</div>

          <van-form @submit="submitNewResume">
            <van-field
              v-model="newResume.title"
              name="title"
              label="简历标题"
              placeholder="请输入简历标题"
              :rules="[{ required: true, message: '请输入简历标题' }]"
            />

            <van-field
              v-model="newResume.description"
              name="description"
              label="简历描述"
              type="textarea"
              placeholder="请输入简历描述"
              rows="3"
              :rules="[{ required: true, message: '请输入简历描述' }]"
            />

            <van-field
              v-model="newResume.content"
              name="content"
              label="简历内容"
              type="textarea"
              placeholder="请输入简历详细内容"
              rows="6"
              :rules="[{ required: true, message: '请输入简历内容' }]"
            />

            <div style="margin: 16px">
              <van-button
                round
                block
                type="primary"
                native-type="submit"
                :loading="submitLoading"
              >
                提交简历
              </van-button>
            </div>
          </van-form>
        </div>

        <!-- 简历列表 -->
        <div v-else-if="activeKey === 2" class="resume-list-section">
          <div class="section-title">简历列表</div>

          <!-- 搜索框 -->
          <div class="search-box">
            <van-field
              v-model="resumeListSearchKeyword"
              placeholder="请输入关键词搜索简历"
              clearable
              @keyup.enter="searchResumeList"
            >
              <template #button>
                <van-button
                  type="primary"
                  size="small"
                  @click="searchResumeList"
                  :loading="resumeListSearchLoading"
                >
                  搜索
                </van-button>
              </template>
            </van-field>
          </div>

          <!-- 简历列表 -->
          <div class="resume-list">
            <van-list
              v-model:loading="resumeListLoading"
              :finished="resumeListFinished"
              finished-text="没有更多了"
              @load="loadResumeList"
            >
              <van-cell
                v-for="item in resumeList"
                :key="item.id"
                :title="item.title"
                :label="`创建时间: ${formatDate(item.createdAt)}`"
                is-link
                @click="showResumeDetail(item)"
              />
            </van-list>
          </div>

          <!-- 简历详情弹窗 -->
          <van-popup
            v-model:show="showResumeDetailPopup"
            position="bottom"
            :style="{ height: '70%' }"
            round
          >
            <div class="detail-content">
              <div class="detail-header">
                <h3>简历详情</h3>
                <van-icon name="cross" @click="closeResumeDetail" />
              </div>
              <div class="detail-body">
                <div v-if="selectedResume">
                  <p><strong>简历标题:</strong> {{ selectedResume.title }}</p>
                  <p>
                    <strong>创建时间:</strong>
                    {{ formatDate(selectedResume.createdAt) }}
                  </p>
                  <p>
                    <strong>简历描述:</strong> {{ selectedResume.description }}
                  </p>
                  <p><strong>简历内容:</strong></p>
                  <div class="resume-content">{{ selectedResume.content }}</div>
                </div>
              </div>
            </div>
          </van-popup>
        </div>

        <!-- 简历移除 -->
        <div v-else-if="activeKey === 3" class="resume-remove-section">
          <div class="section-title">简历移除</div>

          <!-- 简历选择器 -->
          <div class="resume-selector">
            <van-field
              v-model="selectedResumeId"
              label="选择简历"
              placeholder="请输入简历ID或选择简历"
              readonly
              @click="showResumePicker = true"
            />
            <van-button
              type="danger"
              size="small"
              @click="removeResume"
              :loading="removeLoading"
              :disabled="!selectedResumeId"
            >
              移除简历
            </van-button>
          </div>

          <!-- 简历选择弹窗 -->
          <van-popup
            v-model:show="showResumePicker"
            position="bottom"
            :style="{ height: '50%' }"
            round
          >
            <div class="picker-content">
              <div class="picker-header">
                <h3>选择要移除的简历</h3>
                <van-icon name="cross" @click="showResumePicker = false" />
              </div>
              <div class="picker-body">
                <van-cell
                  v-for="item in allResumes"
                  :key="item.id"
                  :title="item.title"
                  :label="`创建时间: ${formatDate(item.createdAt)}`"
                  @click="selectResume(item)"
                  is-link
                />
              </div>
            </div>
          </van-popup>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from "vue";
import { useRouter } from "vue-router";
import {
  NavBar,
  Sidebar,
  SidebarItem,
  List,
  Cell,
  Popup,
  Icon,
  Toast,
  Field,
  Button,
  Form,
  Dialog,
} from "vant";
import httpd from "../../utils/httpd.js";

const router = useRouter();

// 侧边栏状态
const activeKey = ref(0);

// 投递简历移除相关
const deliverySearchKeyword = ref("");
const deliverySearchLoading = ref(false);
const deliveryResumeList = ref([]);
const deliveryLoading = ref(false);
const deliveryFinished = ref(false);
const showDeliveryDetailPopup = ref(false);
const selectedDeliveryResume = ref(null);

// 新增简历相关
const newResume = ref({
  title: "",
  description: "",
  content: "",
});
const submitLoading = ref(false);

// 简历列表相关
const resumeListSearchKeyword = ref("");
const resumeListSearchLoading = ref(false);
const resumeList = ref([]);
const resumeListLoading = ref(false);
const resumeListFinished = ref(false);
const showResumeDetailPopup = ref(false);
const selectedResume = ref(null);

// 简历移除相关
const selectedResumeId = ref("");
const removeLoading = ref(false);
const showResumePicker = ref(false);
const allResumes = ref([]);

// 返回上一页
const goBack = () => {
  router.back();
};

// 侧边栏切换
const onSidebarChange = (index) => {
  activeKey.value = index;
  if (index === 0 && deliveryResumeList.value.length === 0) {
    loadDeliveryResumes();
  } else if (index === 2 && resumeList.value.length === 0) {
    loadResumeList();
  } else if (index === 3 && allResumes.value.length === 0) {
    loadAllResumes();
  }
};

// 格式化日期
const formatDate = (dateString) => {
  if (!dateString) return "";
  const date = new Date(dateString);
  return date.toLocaleDateString("zh-CN");
};

// ========== 投递简历移除功能 ==========
const searchDeliveryResumes = async () => {
  deliverySearchLoading.value = true;
  try {
    const response = await httpd.get("/api/v1/company/company-resume-remove", {
      params: { keyword: deliverySearchKeyword.value },
    });
    if (response.status === 200) {
      // 修复 statusCode 为 status
      deliveryResumeList.value = response.data.list || [];
      Toast.success("搜索成功");
    } else {
      Toast.fail(response.message || "搜索失败");
    }
  } catch (error) {
    console.error("搜索投递简历失败:", error);
    Toast.fail("网络错误，请稍后重试");
  } finally {
    deliverySearchLoading.value = false;
  }
};

const loadDeliveryResumes = async () => {
  deliveryLoading.value = true;
  try {
    const response = await httpd.get("/api/v1/company/company-resume-remove");
    if (response.status === 200) {
      // 修复 statusCode 为 status
      deliveryResumeList.value = response.data.list || [];
      deliveryFinished.value = true;
    } else {
      Toast.fail(response.message || "获取投递简历列表失败");
    }
  } catch (error) {
    console.error("获取投递简历列表失败:", error);
    Toast.fail("网络错误，请稍后重试");
  } finally {
    deliveryLoading.value = false;
  }
};

const removeDeliveryResume = async (item) => {
  if (!item.removing) item.removing = false; // 初始化 item.removing
  try {
    await Dialog.confirm({
      title: "确认移除",
      message: `确定要移除简历"${item.title}"吗？`,
    });

    item.removing = true;
    const response = await httpd.delete(
      `/api/v1/company/company-resume-remove/${item.id}`
    );
    if (response.status === 200) {
      // 修复 statusCode 为 status
      Toast.success("移除成功");
      // 从列表中移除
      const index = deliveryResumeList.value.findIndex(
        (resume) => resume.id === item.id
      );
      if (index > -1) {
        deliveryResumeList.value.splice(index, 1);
      }
    } else {
      Toast.fail(response.message || "移除失败");
    }
  } catch (error) {
    if (error !== "cancel") {
      // 忽略取消操作的错误
      console.error("移除投递简历失败:", error);
      Toast.fail("网络错误，请稍后重试");
    }
  } finally {
    item.removing = false;
  }
};

const showDeliveryDetail = (item) => {
  selectedDeliveryResume.value = item;
  showDeliveryDetailPopup.value = true;
};

const closeDeliveryDetail = () => {
  showDeliveryDetailPopup.value = false;
  selectedDeliveryResume.value = null;
};

// ========== 新增简历功能 ==========
const submitNewResume = async (values) => {
  submitLoading.value = true;
  try {
    const response = await httpd.post(
      "/api/v1/company/company-resume-add",
      values
    );
    if (response.status === 200) {
      // 修复 statusCode 为 status
      Toast.success("简历添加成功");
      // 重置表单
      newResume.value = {
        title: "",
        description: "",
        content: "",
      };
    } else {
      Toast.fail(response.message || "简历添加失败");
    }
  } catch (error) {
    console.error("添加简历失败:", error);
    Toast.fail("网络错误，请稍后重试");
  } finally {
    submitLoading.value = false;
  }
};

// ========== 简历列表功能 ==========
const searchResumeList = async () => {
  resumeListSearchLoading.value = true;
  try {
    const response = await httpd.get("/api/v1/company/company-resume-list", {
      params: { keyword: resumeListSearchKeyword.value },
    });
    if (response.status === 200) {
      // 修复 statusCode 为 status
      resumeList.value = response.data.list || [];
      Toast.success("搜索成功");
    } else {
      Toast.fail(response.message || "搜索失败");
    }
  } catch (error) {
    console.error("搜索简历列表失败:", error);
    Toast.fail("网络错误，请稍后重试");
  } finally {
    resumeListSearchLoading.value = false;
  }
};

const loadResumeList = async () => {
  resumeListLoading.value = true;
  try {
    const response = await httpd.get("/api/v1/company/company-resume-list");
    if (response.status === 200) {
      // 修复 statusCode 为 status
      resumeList.value = response.data.list || [];
      resumeListFinished.value = true;
    } else {
      Toast.fail(response.message || "获取简历列表失败");
    }
  } catch (error) {
    console.error("获取简历列表失败:", error);
    Toast.fail("网络错误，请稍后重试");
  } finally {
    resumeListLoading.value = false;
  }
};

const showResumeDetail = (item) => {
  selectedResume.value = item;
  showResumeDetailPopup.value = true;
};

const closeResumeDetail = () => {
  showResumeDetailPopup.value = false;
  selectedResume.value = null;
};

// ========== 简历移除功能 ==========
const loadAllResumes = async () => {
  try {
    const response = await httpd.get("/api/v1/company/company-resume-list");
    if (response.status === 200) {
      // 修复 statusCode 为 status
      allResumes.value = response.data.list || [];
    } else {
      Toast.fail(response.message || "获取简历列表失败");
    }
  } catch (error) {
    console.error("获取简历列表失败:", error);
    Toast.fail("网络错误，请稍后重试");
  }
};

const selectResume = (item) => {
  selectedResumeId.value = item.id;
  showResumePicker.value = false;
};

const removeResume = async () => {
  if (!selectedResumeId.value) {
    Toast.fail("请先选择要移除的简历");
    return;
  }

  try {
    await Dialog.confirm({
      title: "确认移除",
      message: "确定要移除选中的简历吗？此操作不可恢复。",
    });

    removeLoading.value = true;
    const response = await httpd.delete(
      `/api/v1/company/company-resume-remove/${selectedResumeId.value}`
    );
    if (response.status === 200) {
      // 修复 statusCode 为 status
      Toast.success("简历移除成功");
      selectedResumeId.value = ""; // 清空选中的简历 ID
      // 重新加载简历列表
      loadAllResumes();
    } else {
      Toast.fail(response.message || "简历移除失败");
    }
  } catch (error) {
    if (error !== "cancel") {
      // 忽略取消操作的错误
      console.error("移除简历失败:", error);
      Toast.fail("网络错误，请稍后重试");
    }
  } finally {
    removeLoading.value = false;
  }
};

onMounted(() => {
  // 默认加载投递简历列表
  loadDeliveryResumes();
});
</script>

<style scoped lang="less">
.fujianjianli-page {
  min-height: 100vh;
  background: #f7f8fa;
}

.fujianjianli-container {
  display: flex;
  height: calc(100vh - 46px);
}

.sidebar {
  width: 100px;
  background: #fff;
  border-right: 1px solid #ebedf0;
}

.content {
  flex: 1;
  padding: 16px;
  overflow-y: auto;
}

.section-title {
  font-size: 18px;
  font-weight: 600;
  color: #323233;
  margin-bottom: 16px;
  padding-left: 8px;
}

.search-box {
  margin-bottom: 16px;
}

.resume-list {
  .van-cell {
    margin-bottom: 8px;
    border-radius: 8px;
    background: #fff;
  }
}

// 新增简历模块样式
.add-resume-section {
  .van-form {
    background: #fff;
    border-radius: 8px;
    padding: 16px;
  }
}

// 简历移除模块样式
.resume-remove-section {
  .resume-selector {
    display: flex;
    align-items: center;
    gap: 12px;
    margin-bottom: 20px;

    .van-field {
      flex: 1;
    }

    .van-button {
      flex-shrink: 0;
    }
  }
}

.picker-content {
  padding: 20px;
  height: 100%;
  display: flex;
  flex-direction: column;
}

.picker-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 16px;
  border-bottom: 1px solid #ebedf0;

  h3 {
    font-size: 18px;
    font-weight: 600;
    color: #323233;
    margin: 0;
  }

  .van-icon {
    font-size: 20px;
    color: #969799;
    cursor: pointer;
  }
}

.picker-body {
  flex: 1;
  overflow-y: auto;
}

.detail-content {
  padding: 20px;
  height: 100%;
  display: flex;
  flex-direction: column;
}

.detail-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 16px;
  border-bottom: 1px solid #ebedf0;

  h3 {
    font-size: 18px;
    font-weight: 600;
    color: #323233;
    margin: 0;
  }

  .van-icon {
    font-size: 20px;
    color: #969799;
    cursor: pointer;
  }
}

.detail-body {
  flex: 1;
  line-height: 1.6;
  color: #666;
  font-size: 14px;
  overflow-y: auto;

  p {
    margin-bottom: 12px;
  }

  .resume-content {
    background: #f7f8fa;
    padding: 12px;
    border-radius: 6px;
    margin-top: 8px;
    white-space: pre-wrap;
  }
}

// 深度样式
:deep(.van-sidebar-item) {
  font-size: 14px;
}

:deep(.van-sidebar-item--selected) {
  background: #e8f5e8;
  color: #6fb06c;
}

:deep(.van-field__label) {
  color: #323233;
  font-weight: 500;
}

:deep(.van-button--danger) {
  background: #ee0a24;
  border-color: #ee0a24;
}
</style>
